package netty.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.haproxy.HAProxyMessage;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class HAProxyServerHandler extends SimpleChannelInboundHandler<Object> {

    public HAProxyServerHandler() {
        log.info(">>> init {}", this.toString());
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            // Do something with msg
            log.info("receive data: {}, {}", msg, ctx.channel().remoteAddress());
            if (msg instanceof HAProxyMessage) {
                log.info("proxy message: " + msg);
            } else if (msg instanceof ByteBuf) {
                log.info("bytebuf message: " + ByteBufUtil.prettyHexDump((ByteBuf) msg));
            }
        } finally {
//            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}